<?php
define('CLI',1);
define('DEBUG',1);
include "lib/bi/core/commandlinecolors.php";
include 'lib/bi/core/link.php';
include 'lib/bi/core/helpers.php';
include 'lib/bi/core/database.class.php';
clicolor_begin('white');
array_shift($_SERVER['argv']);
$func=array_shift($_SERVER['argv']);
$param=&$_SERVER['argv'];

$state=Array();
$statefn='lib/bi/cli/states/'.$_SERVER['LOGNAME'].'.php';
if(!file_exists($statefn))file_put_contents($statefn,'<? $state=Array(); ?>');
	
$fn="lib/bi/cli/".$func.".php";


try{
	if($func!='database-config'){
		include 'config/database.php';
		include $statefn;
		print_var($state);	
	}
			
	
	if(isset($state[APPLICATION])){
		require_once 'apps/'.$state[APPLICATION].'/application.'.$state[APPLICATION].'.php';
		$clsn=$state[APPLICATION].'Application';
		$app=new $clsn(Array('name'=>$state[APPLICATION]));	
		if(isset($state[MODULE])){
			$clsn=$state[MODULE].'Module';
			$fn='apps/'.$state[APPLICATION].'/module.'.strtolower($state[MODULE]).'.php';
			echo $fn;
			require_once $fn;
			$module=new $clsn(Array());
		}
	}
	if(isset($state['table'])){
		$clsn=$state['table'].'Table';
		$table=new $clsn();
		if(isset($state['record_id'])){
			$record=$table->getById($state['record_id']);
		}
	}
	
	
	if(!file_exists($fn)){
		throw new Exception('Command not recognized');
	};
	include $fn;
}catch(Exception $e){
	clicolor_end();
	clicolor_begin('light_red');
	echo $e->getMessage();
};
clicolor_end();

file_put_contents($statefn,'<? $state='.var_export($state,1).'; ?>');
echo "\n";
